<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Models\ProjectModel;
use App\Http\Models\CaseModel;
use App\Http\Models\CategoryModel;

class CaseController extends HomeController
{
    // 获取编辑推荐
    public function hotList(Request $request)
    {
        try{
            $pagesize = $request->input('pagesize', 9);
            $pageno = $request->input('pageno', 1);
            $cate = $request->input('cate', 0);
            $search = $request->input('search', '');

            $sqlRow = ' `is_recommend` = 2 AND `is_top` = 1 ';
            if($search !== '') {
                $sqlRow .= " AND `title` LIKE '".$search."%' ";
            }
            if ($cate > 4) {
                $sqlRow .= " AND find_in_set(".$cate.", `category`) ";
            } else {
                $cateids = array_keys(CategoryModel::get_all($cate));
                if($cateids) {
                    $sqlRow .= " AND ( ";
                    foreach ($cateids as &$id) {
                        $id = "find_in_set(" . $id . ", `category`)";
                    }
                    $sqlRow .= implode(' OR ', $cateids) . " ) ";
                }
            }
            $orderKey = 'sort';
            $data = ProjectModel::whereRaw($sqlRow)
                ->orderBy($orderKey,"desc")
                ->skip(($pageno-1) * $pagesize)
                ->take($pagesize)
                ->get();
            return response()->json(build_result(["info"=>build_project_info($data), "pagesize" => $pagesize, "pageno" => $pageno]));
        }catch(\Exception $e) {
            return response()->json(build_result('', '10001', $e->getMessage()));   
        }
    }

    // 获取每周排行
    public function weekList(Request $request)
    {
        try{
            $pagesize = $request->input('pagesize', 9);
            $pageno = $request->input('pageno', 1);
            $cases = CaseModel::get_week_rank($pageno, $pagesize);
            $caseIds = array_keys($cases);
            $projects = ProjectModel::whereIn('id', $caseIds)->get();
            return response()->json(build_result(["info"=>build_project_info($projects), "pagesize" => $pagesize, "pageno" => $pageno]));
        } catch ( \Exception $e) {
            return response()->json(build_result('', '10002', $e->getMessage()));
        }
    }

    // 获取每月排行
    public function monthList(Request $request)
    {
        try{
            $pagesize = $request->input('pagesize', 9);
            $pageno = $request->input('pageno', 1);
            $cases = CaseModel::get_month_rank($pageno, $pagesize);
            $caseIds = array_keys($cases);
            $projects = ProjectModel::whereIn('id', $caseIds)->get();
            return response()->json(build_result(["info"=>build_project_info($projects), "pagesize" => $pagesize, "pageno" => $pageno]));
        } catch ( \Exception $e) {
            return response()->json(build_result('', '10002', $e->getMessage()));   
        }
    }
}

